<template>
    <div class="profile-container">
        <el-card class="box-card" style="margin: 10px auto;">
            <template #header>
                <div class="card-header">
                    <span>个人信息</span>
                </div>
            </template>

            <el-descriptions :column="1" border>
                <el-descriptions-item label="姓名">
                    {{ userInfo.name || '—' }}
                </el-descriptions-item>
                <el-descriptions-item label="用户名">
                    {{ userInfo.loginName || '—' }}
                </el-descriptions-item>
                <el-descriptions-item label="手机号">
                    {{ userInfo.phone || '—' }}
                </el-descriptions-item>
                <el-descriptions-item label="邮箱">
                    <template v-if="userInfo.email">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <span>{{ userInfo.email }}</span>
                            <el-button type="text" size="small" @click="openBindEmailDialog(true)">
                                修改邮箱
                            </el-button>
                        </div>
                    </template>
                    <template v-else>
                        <el-button type="primary" size="small" @click="openBindEmailDialog(false)">
                            绑定邮箱
                        </el-button>
                    </template>
                </el-descriptions-item>

                <el-descriptions-item label="密码">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <span>********</span>
                        <el-button type="text" size="small" @click="openPasswordDialog">
                            修改密码
                        </el-button>
                    </div>
                </el-descriptions-item>

                <el-descriptions-item label="所属部门">
                    {{ userInfo.departmentName || '—' }}
                </el-descriptions-item>
                <el-descriptions-item label="所属公司">
                    {{ userInfo.companyName || '—' }}
                </el-descriptions-item>
            </el-descriptions>

            <div style="margin-top: 20px; text-align: right;">
                <el-button type="primary" @click="$router.back()">返回</el-button>
            </div>
        </el-card>

        <!-- 邮箱绑定 -->
        <el-dialog v-model="bindEmailDialogVisible" :title="dialogTitle" width="400px" @close="resetBindForm">
            <el-form ref="bindEmailFormRef" :model="bindEmailForm" :rules="bindEmailRules" label-width="80px">
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="bindEmailForm.email" placeholder="请输入新邮箱" clearable />
                </el-form-item>

                <el-form-item label="验证码" prop="code">
                    <div style="display: flex; gap: 10px">
                        <el-input v-model="bindEmailForm.code" placeholder="请输入验证码" style="flex: 1" clearable />
                        <el-button type="primary" :disabled="countdown > 0 || !canSendCode"
                            @click="sendVerificationCode">
                            <span v-if="countdown > 0">{{ countdown }}s 后重试</span>
                            <span v-else>获取验证码</span>
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="bindEmailDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmBindEmail" :loading="binding">
                    确定
                </el-button>
            </template>
        </el-dialog>

        <!-- 密码修改 -->
        <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px" @close="resetPasswordForm">

            <el-form v-if="passwordStep === 1" ref="oldPasswordFormRef" :model="oldPasswordForm"
                :rules="oldPasswordRules" label-width="100px">
                <el-form-item label="当前密码" prop="oldPassword">
                    <el-input v-model="oldPasswordForm.oldPassword" type="password" placeholder="请输入当前登录密码"
                        show-password />
                </el-form-item>
            </el-form>

            <el-form v-else ref="newPasswordFormRef" :model="newPasswordForm" :rules="newPasswordRules"
                label-width="100px">
                <el-form-item label="手机号码">
                    {{ userInfo.phone }}
                </el-form-item>
                <el-form-item label="验证码" prop="verificationCode">
                    <el-row :gutter="10">
                        <el-col :span="16">
                            <el-input v-model="newPasswordForm.verificationCode" placeholder="请输入验证码"
                                prefix-icon="Message" />
                        </el-col>
                        <el-col :span="8">
                            <el-button type="primary" @click="sendPhoneVerificationCode" style="width: 100%;"
                                :loading="sending">
                                {{ phoneCountDown > 0 ? `${phoneCountDown}s 后重发` : '获取验证码' }}
                            </el-button>
                        </el-col>
                    </el-row>
                </el-form-item>

                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="newPasswordForm.newPassword" type="password" placeholder="请输入新密码"
                        show-password />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="newPasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码"
                        show-password />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="passwordDialogVisible = false">取消</el-button>
                <el-button v-if="passwordStep === 1" type="primary" @click="validateOldPassword" :loading="validating">
                    下一步
                </el-button>
                <el-button v-else type="primary" @click="submitNewPassword" :loading="updating">
                    确定修改
                </el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const userInfo = ref({})
const bindEmailDialogVisible = ref(false)
const bindEmailFormRef = ref(null)
const binding = ref(false)
const sending = ref(false)
const router = useRouter()

// 【新增】对话框标题，用于区分“绑定”还是“修改”
const dialogTitle = ref('绑定邮箱')

// 表单数据
const bindEmailForm = reactive({
    email: '',
    code: ''
})

const checkEmail = (rule, value, callback) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (value == '' || value == null) {
        callback(new Error('邮箱不能为空'))
    } else if (!emailRegex.test(value)) {
        callback(new Error('邮箱格式不正确'))
    } else {
        callback()
    }
}

const checkEmailCode = (rule, value, callback) => {
    if (value === '' || value == null) {
        callback(new Error('请输入验证码'))
    } else {
        callback()
    }
}

const bindEmailRules = reactive({
    email: [{ validator: checkEmail, trigger: 'blur' }],
    code: [{ validator: checkEmailCode, trigger: 'blur' }]
})

// 倒计时
const countdown = ref(0)
const timer = ref(null)

// 计算是否可以发送验证码（邮箱合法）
const canSendCode = computed(() => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return emailRegex.test(bindEmailForm.email)
})


// 【新增】密码相关状态
const passwordDialogVisible = ref(false)
const passwordStep = ref(1) // 1: 验证旧密码, 2: 设置新密码
const validating = ref(false) // 验证旧密码加载状态
const updating = ref(false)   // 更新新密码加载状态

// 步骤 1: 验证旧密码表单
const oldPasswordFormRef = ref(null)
const oldPasswordForm = reactive({
    oldPassword: ''
})

const oldPasswordRules = reactive({
    oldPassword: [
        { required: true, message: '请输入当前登录密码', trigger: 'blur' },
    ]
})

// 步骤 2: 修改新密码表单
const newPasswordFormRef = ref(null)
const newPasswordForm = reactive({
    phone: userInfo.value.phone,
    verificationCode: '',
    newPassword: '',
    confirmPassword: ''
})

const checkVerificationCode = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入验证码'))
    } else {
        callback()
    }
}

const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== newPasswordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
    } else {
        callback()
    }
}

const newPasswordRules = reactive({
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' }
    ],
    verificationCode: [{ validator: checkVerificationCode, trigger: 'blur' }]
})


// 【修改】打开绑定/修改邮箱对话框
const openBindEmailDialog = (isModify = false) => {
    // 根据是否传入 true 来判断是修改还是绑定
    if (isModify) {
        dialogTitle.value = '修改邮箱'
    } else {
        dialogTitle.value = '绑定邮箱'
    }
    bindEmailDialogVisible.value = true
}

// 打开修改密码对话框
const openPasswordDialog = () => {
    resetPasswordForm() // 确保每次打开都从第一步开始并重置表单
    passwordDialogVisible.value = true
}

// 验证旧密码
const validateOldPassword = async () => {
    await oldPasswordFormRef.value?.validate(async (valid) => {
        if (!valid) return

        validating.value = true
        try {
            const res = await axios.post('/api/basic/auth/checkPassword', null, { params: { password: oldPasswordForm.oldPassword } })
            if (res.data.code === 5200) {
                // 校验成功，切换到第二步
                passwordStep.value = 2
                newPasswordFormRef.value?.resetFields() // 确保新密码表单是干净的
            } else {
                ElMessage.error(res.data.msg || '当前密码不正确，请重新输入')
            }
        } catch (error) {
            ElMessage.error('网络错误，请稍后重试')
            console.error('密码校验错误:', error)
        } finally {
            validating.value = false
        }
    })
}

// 手机验证码倒计时
const phoneCountDown = ref(0)

// 发送手机验证码
const sendPhoneVerificationCode = async () => {
    sending.value = true

    try {
        const res = await axios.get('/api/basic/auth/sendVerifyCode', { params: { phone: userInfo.value.phone } })
        if (res.data.code === 5200) {
            // 启动倒计时
            phoneCountDown.value = 60
            const timer = setInterval(() => {
                if (phoneCountDown.value > 0) {
                    phoneCountDown.value--
                } else {
                    clearInterval(timer)
                }
            }, 1000)
        }
    } catch (error) {
        ElMessage.error(error.message || '验证码发送失败')

    } finally {
        sending.value = false
    }
}

// 提交新密码
const submitNewPassword = async () => {
    await newPasswordFormRef.value?.validate(async (valid) => {
        if (!valid) return

        updating.value = true
        try {
            const res = await axios.post('/api/basic/enterprise/updatePassword', null, {
                params: {
                    phone: userInfo.value.phone,
                    verificationCode: newPasswordForm.verificationCode,
                    newPassword: newPasswordForm.newPassword
                }
            })

            if (res.data.code === 5200) {
                ElMessage.success('密码修改成功，请重新登录')
                passwordDialogVisible.value = false
                loginOut()
            } else {
                ElMessage.error(res.data.msg || '密码修改失败')
            }
        } catch (error) {
            ElMessage.error('网络错误，请稍后重试')
            console.error('修改密码错误:', error)
        } finally {
            updating.value = false
        }
    })
}

// 重置修改密码对话框状态和表单
const resetPasswordForm = () => {
    passwordStep.value = 1
    oldPasswordForm.oldPassword = ''
    newPasswordForm.newPassword = ''
    newPasswordForm.verificationCode = ''
    newPasswordForm.confirmPassword = ''
    oldPasswordFormRef.value?.resetFields()
    newPasswordFormRef.value?.resetFields()
}

// 获取用户信息
const getUserInfo = async () => {

    try {
        const res = await axios.get('/api/basic/enterprise/staffById')
        if (res.data.code === 5200) {
            userInfo.value = res.data.staff
        } else {
            ElMessage.error(res.data.msg || '获取失败')
        }
    } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
    }
}

// 发送验证码
const sendVerificationCode = async () => {
    if (!canSendCode.value) {
        ElMessage.warning('请先输入正确的邮箱')
        return
    }

    // 可以在这里加一个额外的规则：修改邮箱时，新邮箱不能和旧邮箱一样
    if (dialogTitle.value === '修改邮箱' && bindEmailForm.email === userInfo.value.email) {
        ElMessage.warning('新邮箱不能与原邮箱相同')
        return
    }

    try {
        const res = await axios.get('/api/basic/email/sendEmail', { params: { email: bindEmailForm.email } })
        if (res.data.code === 5200) {
            ElMessage.success('验证码已发送，请注意查收')
            // 开始倒计时
            countdown.value = 60
            clearInterval(timer.value)
            timer.value = setInterval(() => {
                if (countdown.value > 0) {
                    countdown.value--
                } else {
                    clearInterval(timer.value)
                }
            }, 1000)
        } else {
            ElMessage.error(res.data.msg || '发送失败')
        }
    } catch (error) {
        ElMessage.error('发送验证码失败，请稍后重试')
        console.error('发送验证码错误:', error)
    }
}

// 确认绑定/修改邮箱
const confirmBindEmail = async () => {
    await bindEmailFormRef.value?.validate(async (valid) => {
        if (!valid) return

        binding.value = true
        try {
            // 注意：因为是共用一个接口，所以逻辑与原代码保持一致
            // 确保后端 /api/basic/enterprise/updateEmail 接口能处理绑定和修改两种情况
            const res = await axios.post('/api/basic/enterprise/updateEmail', {
                email: bindEmailForm.email,
                code: bindEmailForm.code,
                staffId: localStorage.getItem('staffId') // 最好在前端显式传递用户ID
            })

            if (res.data.code === 5200) {
                // 根据对话框标题给出不同的提示
                ElMessage.success(dialogTitle.value === '绑定邮箱' ? '邮箱绑定成功！' : '邮箱修改成功！')
                bindEmailDialogVisible.value = false
                // 刷新用户信息
                getUserInfo()
            } else {
                ElMessage.error(res.data.msg || (dialogTitle.value === '绑定邮箱' ? '绑定失败' : '修改失败'))
            }
        } catch (error) {
            ElMessage.error('操作失败，请检查验证码或网络')
            console.error('绑定/修改邮箱错误:', error)
        } finally {
            binding.value = false
        }
    })
}

// 重置表单和倒计时
const resetBindForm = () => {
    bindEmailForm.email = ''
    bindEmailForm.code = ''
    countdown.value = 0
    clearInterval(timer.value)
    bindEmailFormRef.value?.resetFields()
    // 重置对话框标题为默认（如果需要）
    dialogTitle.value = '绑定邮箱'
}

const loginOut = async () => {
    try {
        const res = await axios.get('/api/basic/auth/loginOut')

        if (res.data.code === 5200) {
            sessionStorage.clear();
            // 跳转到登录页
            router.push({ name: 'login' })
        } else {
            ElMessage.error("退出登录失败")
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

onMounted(() => {
    getUserInfo()
})
</script>

<style scoped>
/* 保持原样 */
.profile-container {
    min-height: calc(100vh - 80px);
    background-color: #f5f7fa;
    padding: 20px 0;
}

.card-header {
    font-size: 18px;
    font-weight: bold;
}
</style>
